#ifndef FS_H
#define FS_H
#include <SD.h>

#include "domino.h"

#define chipSelect 4

bool sd_enable()
{
	//pinMode(10, OUTPUT);
	digitalWrite(10, LOW);
	if (!SD.begin(chipSelect)) {
		return false;
	}
	return true;
}

bool sd_disable()
{
	digitalWrite(10, HIGH);
	digitalWrite(chipSelect, LOW);
	return true;
}

// {{{
bool loadConfigurationFromSD(char *filename)
{
	char cmd[20];
	char pos = 0;
	char b;


	if (!sd_enable()) {
		sd_disable();
		return false;
	}
	// Card found. Reading contents:
	File cfgFile = SD.open(filename, FILE_READ);
	if (cfgFile) {
		b = cfgFile.read();
		while (b>0 && b<250) {
			switch (b) {
			case 10:
			case 0:
				break;
			case 13:
				Serial.println(cmd);
				//processInstruction(cmd);
 				pos = 0;
				break;
			default:
				if (pos<20){
					cmd[pos] = b;
					pos++;
					cmd[pos] = 0;
				}
			}
			b = cfgFile.read();
		}
		Serial.println("D:sdok");

	}
	cfgFile.close();
	sd_disable();
	return true;
}
// }}}

// {{{
bool writeLog(char *filename, char *data)
{
	if (!sd_enable()) {
		sd_disable();
		return false;
	}
	File dataFile = SD.open(filename, FILE_WRITE);
	if (dataFile) {
		dataFile.println(data);
		dataFile.close();
	} else {
		return false;
	}
	return strlen(data);
}
// }}}

// {{{
bool readLog(char *filename, char *buffer)
{
	char b;
	if (!sd_enable()) {
		sd_disable();
		return false;
	}
	File logFile = SD.open(filename, FILE_READ);
	if (logFile) {
		while (b = logFile.read()) {
			/// @todo Enable this
			//strncat(buffer,sizeof(buffer),b);
		}
	}
	logFile.close();
	sd_disable();
}
// }}}
#endif

